package com.inifitness.message.filter;

import java.io.IOException;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import com.inifitness.common.exceptions.BizException;
import com.inifitness.common.tools.ResponseUtils;

import cn.hutool.core.text.CharSequenceUtil;
import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * JWT token 校验过滤器
 *
 * @author sunjinfeng
 * @since 2023/04/13
 */
@Log4j2
@NoArgsConstructor
public class AppIdValidationFilter extends OncePerRequestFilter {

  /**
   * 从请求中获取 JWT Token，校验 JWT Token 是否合法
   * <p>
   * 如果合法则将 Authentication 设置到 Spring Security Context 上下文中 如果不合法则清空 Spring Security Context
   * 上下文，并直接返回响应
   */
  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
      FilterChain filterChain) throws ServletException, IOException {
    String appid = request.getHeader(HttpHeaders.AUTHORIZATION);
    try {
      if (CharSequenceUtil.isNotBlank(appid)) {
        log.info("appid={}",appid);
      }
    } catch (BizException ex) {
      //this is very important, since it guarantees the user is not authenticated at all
      SecurityContextHolder.clearContext();
      ResponseUtils.writeErrMsg(response, ex.getResultCode());
      return;
    }

    filterChain.doFilter(request, response);
  }
}
